<template>
  <div class="step-panel">
    <h2>{{ stepTitle }}</h2>

    <!-- 子步骤导航 -->
    <div class="substeps-nav">
      <div
        v-for="(substep, i) in substeps"
        :key="i"
        class="substep-item"
        :class="{
          'substep-active': currentSubstep === i + 1,
          'substep-completed': currentSubstep > i + 1,
          'substep-disabled': currentSubstep < i + 1,
        }"
        @click="navigateToSubstep(i + 1)"
      >
        <span>{{ i + 1 }}</span>
        <span>{{ substep.title }}</span>
      </div>
    </div>

    <!-- 子步骤1：基础信息 -->
    <div v-if="currentSubstep === 1" class="substep-content">
      <h3>老人基础信息</h3>
      <div class="form-grid">
        <div class="form-group">
          <label>姓名 <span class="required">*</span></label>
          <input
            type="text"
            v-model="localFormData.elder.name"
            placeholder="请输入老人姓名"
          />
        </div>
        <div class="form-group">
          <label>身份证号 <span class="required">*</span></label>
          <input
            type="text"
            v-model="localFormData.elder.idCard"
            placeholder="请输入18位身份证号"
          />
        </div>
        <div class="form-group">
          <label>性别</label>
          <div class="radio-group">
            <label>
              <input
                type="radio"
                value="男"
                v-model="localFormData.elder.gender"
              />
              男
            </label>
            <label>
              <input
                type="radio"
                value="女"
                v-model="localFormData.elder.gender"
              />
              女
            </label>
          </div>
        </div>
        <div class="form-group">
          <label>出生日期</label>
          <input type="date" v-model="localFormData.elder.birthDate" />
        </div>
        <div class="form-group">
          <label>年龄</label>
          <input
            type="number"
            v-model="localFormData.elder.age"
            min="0"
            placeholder="请输入年龄"
          />
        </div>
        <div class="form-group">
          <label>联系电话 <span class="required">*</span></label>
          <input
            type="tel"
            v-model="localFormData.elder.contact"
            placeholder="请输入联系电话"
          />
        </div>
        <div class="form-group">
          <label>家庭住址 <span class="required">*</span></label>
          <input
            type="text"
            v-model="localFormData.elder.address"
            placeholder="请输入家庭住址"
          />
        </div>
        <div class="form-group">
          <label>民族</label>
          <el-select
            v-model="localFormData.elder.ethnicity"
            placeholder="请选择民族"
            clearable
          >
            <el-option
              v-for="dict in ethnicity"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>政治面貌</label>
          <el-select
            v-model="localFormData.elder.politicalStatus"
            placeholder="请选择政治面貌"
            clearable
          >
            <el-option
              v-for="dict in political_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>宗教信仰</label>
          <el-select
            v-model="localFormData.elder.religiousBelief"
            placeholder="请选择宗教信仰"
            clearable
          >
            <el-option
              v-for="dict in religious_belief"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>婚姻状况</label>
          <el-select
            v-model="localFormData.elder.maritalStatus"
            placeholder="请选择婚姻状况"
            clearable
          >
            <el-option
              v-for="dict in marital_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>文化程度</label>
          <el-select
            v-model="localFormData.elder.education"
            placeholder="请选择文化程度"
            clearable
          >
            <el-option
              v-for="dict in educational_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>经济来源</label>
          <el-select
            v-model="localFormData.elder.incomeSource"
            placeholder="请选择经济来源"
            clearable
          >
            <el-option
              v-for="dict in source_of_income"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>爱好</label>
          <el-select
            v-model="localFormData.elder.hobby"
            placeholder="请选择爱好"
            clearable
          >
            <el-option
              v-for="dict in hobby"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>医疗保障</label>
          <el-select
            v-model="localFormData.elder.medicalInsurance"
            placeholder="请选择医疗保障"
            clearable
          >
            <el-option
              v-for="dict in medical_insurance"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </div>
        <div class="form-group">
          <label>医保卡号</label>
          <input
            type="text"
            v-model="localFormData.elder.medicalCardNo"
            placeholder="请输入医保卡号"
          />
        </div>
      </div>
      <div class="substep-actions">
        <button @click="saveElderAndNext" :disabled="!isElderInfoValid || elderLoading">
          {{ elderLoading ? '保存中...' : '下一步' }}
        </button>
      </div>
    </div>

    <!-- 子步骤2：家属信息 -->
    <div v-if="currentSubstep === 2" class="substep-content">
      <h3>家属信息</h3>
      <div class="family-members">
        <div
          v-for="(member, index) in localFormData.familyMembers"
          :key="index"
          class="family-member-card"
        >
          <div class="form-grid">
            <div class="form-group">
              <label>家属姓名 <span class="required">*</span></label>
              <input
                type="text"
                v-model="member.name"
                placeholder="请输入家属姓名"
              />
            </div>
            <div class="form-group">
              <label>联系电话 <span class="required">*</span></label>
              <input
                type="tel"
                v-model="member.contact"
                placeholder="请输入联系电话"
              />
            </div>
            <div class="form-group">
              <label>与老人关系 <span class="required">*</span></label>
              <el-select
                v-model="member.relationship"
                placeholder="请选择与老人关系"
                clearable
              >
                <el-option
                  v-for="dict in relationship_with_the_elderly"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </div>
            <div class="form-group">
              <label>紧急联系人</label>
              <div class="radio-group">
                <label>
                  <input
                    type="radio"
                    value="是"
                    v-model="member.isEmergency"
                  />
                  是
                </label>
                <label>
                  <input
                    type="radio"
                    value="否"
                    v-model="member.isEmergency"
                    checked
                  />
                  否
                </label>
              </div>
            </div>
          </div>
          <button
            type="button"
            class="remove-btn"
            @click="removeFamilyMember(index)"
            :disabled="localFormData.familyMembers.length <= 1"
          >
            - 删除
          </button>
        </div>
      </div>
      <button type="button" class="add-btn" @click="addFamilyMember">
        + 添加家属
      </button>

      <div class="substep-actions">
        <button @click="prevSubstep">上一步</button>
        <button @click="saveFamilyAndNext" :disabled="!isFamilyInfoValid || familyLoading">
          {{ familyLoading ? '保存中...' : '下一步' }}
        </button>
      </div>
    </div>

    <!-- 子步骤3：资料上传 -->
    <div v-if="currentSubstep === 3" class="substep-content">
      <h3>资料上传</h3>
      <div class="upload-group">
        <!-- 一寸照片上传 -->
        <div class="upload-item">
          <label>一寸照片 <span class="required">*</span></label>
          <div class="upload-wrapper">
            <div class="upload-area" @click="triggerFileInput('photo')">
              <input
                type="file"
                accept="image/jpeg,image/png,image/jpg"
                ref="photoInput"
                @change="handleUpload('photo', $event)"
                class="upload-input"
                style="display: none"
              />
              <div v-if="!previewUrls.photo" class="upload-placeholder">
                <span class="upload-icon">+</span>
                <span class="upload-text">点击上传照片</span>
              </div>
              <div v-else class="preview-container">
                <img
                  :src="previewUrls.photo"
                  alt="一寸照片预览"
                  class="preview-image"
                />
              </div>
            </div>
            <div v-if="localFormData.uploads.photo" class="file-info">
              <span class="file-name">{{ localFormData.uploads.photo.name }}</span>
              <span class="file-size">({{ formatFileSize(localFormData.uploads.photo.size) }})</span>
              <button
                type="button"
                class="remove-btn"
                @click.stop="clearUpload('photo')"
              >
                删除
              </button>
            </div>
            <div v-else class="upload-hint">
              支持JPG、PNG格式，文件大小不超过2MB
            </div>
          </div>
        </div>

        <!-- 身份证正面上传 -->
        <div class="upload-item">
          <label>身份证正面 <span class="required">*</span></label>
          <div class="upload-wrapper">
            <div class="upload-area" @click="triggerFileInput('idCardFront')">
              <input
                type="file"
                accept="image/jpeg,image/png,image/jpg"
                ref="idCardFrontInput"
                @change="handleUpload('idCardFront', $event)"
                class="upload-input"
                style="display: none"
              />
              <div v-if="!previewUrls.idCardFront" class="upload-placeholder">
                <span class="upload-icon">+</span>
                <span class="upload-text">点击上传身份证正面</span>
              </div>
              <div v-else class="preview-container">
                <img
                  :src="previewUrls.idCardFront"
                  alt="身份证正面预览"
                  class="preview-image"
                />
              </div>
            </div>
            <div v-if="localFormData.uploads.idCardFront" class="file-info">
              <span class="file-name">{{ localFormData.uploads.idCardFront.name }}</span>
              <span class="file-size">({{ formatFileSize(localFormData.uploads.idCardFront.size) }})</span>
              <button
                type="button"
                class="remove-btn"
                @click.stop="clearUpload('idCardFront')"
              >
                删除
              </button>
            </div>
            <div v-else class="upload-hint">
              请上传清晰的身份证正面照片，支持JPG、PNG格式，文件大小不超过2MB
            </div>
          </div>
        </div>

        <!-- 身份证反面上传 -->
        <div class="upload-item">
          <label>身份证反面 <span class="required">*</span></label>
          <div class="upload-wrapper">
            <div class="upload-area" @click="triggerFileInput('idCardBack')">
              <input
                type="file"
                accept="image/jpeg,image/png,image/jpg"
                ref="idCardBackInput"
                @change="handleUpload('idCardBack', $event)"
                class="upload-input"
                style="display: none"
              />
              <div v-if="!previewUrls.idCardBack" class="upload-placeholder">
                <span class="upload-icon">+</span>
                <span class="upload-text">点击上传身份证反面</span>
              </div>
              <div v-else class="preview-container">
                <img
                  :src="previewUrls.idCardBack"
                  alt="身份证反面预览"
                  class="preview-image"
                />
              </div>
            </div>
            <div v-if="localFormData.uploads.idCardBack" class="file-info">
              <span class="file-name">{{ localFormData.uploads.idCardBack.name }}</span>
              <span class="file-size">({{ formatFileSize(localFormData.uploads.idCardBack.size) }})</span>
              <button
                type="button"
                class="remove-btn"
                @click.stop="clearUpload('idCardBack')"
              >
                删除
              </button>
            </div>
            <div v-else class="upload-hint">
              请上传清晰的身份证反面照片，支持JPG、PNG格式，文件大小不超过2MB
            </div>
          </div>
        </div>
      </div>

      <div class="substep-actions">
        <button @click="prevSubstep">上一步</button>
        <button @click="savePhotosAndComplete" :disabled="!isUploadInfoValid || photoLoading">
          {{ photoLoading ? '上传中...' : '完成第一步' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, shallowRef, getCurrentInstance } from 'vue'
// 在组件脚本开头添加导入
import { ElMessage ,ElMessageBox} from 'element-plus';
import request from '@/utils/request'; // 导入若依框架的请求工具
import { listElderly, getElderly, delElderly, addElderly, updateElderly } from "@/api/le/elderly"
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/le/member"
import { addPendingTasks } from "@/api/le/pendingTasks"

const { proxy } = getCurrentInstance();
const { 
    ethnicity, 
    political_status, 
    marital_status, 
    religious_belief,
    educational_level,
    source_of_income,
    hobby,
    medical_insurance,
    relationship_with_the_elderly,
 } = proxy.useDict(
    "ethnicity", 
    "political_status", 
    "marital_status", 
    "religious_belief", 
    "educational_level", 
    "source_of_income", 
    "hobby",
    "medical_insurance",
    "relationship_with_the_elderly",
);

const props = defineProps({
  formData: {
    type: Object,
    required: true
  },
  currentUser: {
    type: Object,
    default: () => ({
      id: null,
      nickName: "",
      name: "",
      roles: []
    })
  }
})

const emit = defineEmits(['next', 'update:form-data', 'elder-saved'])

// 步骤配置
const stepTitle = '第一步：老人及家属信息'
const substeps = [
  { title: "基础信息" },
  { title: "家属信息" },
  { title: "资料上传" },
]

// 本地状态
const currentSubstep = ref(1)
const localFormData = reactive(JSON.parse(JSON.stringify(props.formData)))

// loading状态
const elderLoading = ref(false)
const familyLoading = ref(false)
const photoLoading = ref(false)

// 文件上传相关
const photoInput = ref(null)
const idCardFrontInput = ref(null)
const idCardBackInput = ref(null)
const previewUrls = shallowRef({
  photo: "",
  idCardFront: "",
  idCardBack: "",
})

// 监听父组件数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, newData)
}, { deep: true })

// 验证逻辑
const isElderInfoValid = computed(() => {
  const e = localFormData.elder
  return !!e.name && !!e.idCard && !!e.address && !!e.contact
})

// 验证家属信息
const isFamilyInfoValid = computed(() => {
  return localFormData.familyMembers.every(
    (member) => !!member.name && !!member.contact && !!member.relationship
  )
})

const isUploadInfoValid = computed(() => {
  const u = localFormData.uploads
  return !!u.photo && !!u.idCardFront && !!u.idCardBack
})

// 导航方法
const navigateToSubstep = (substep) => {
  if (substep <= currentSubstep.value) {
    currentSubstep.value = substep
    updateFormData()
  }
}

const nextSubstep = () => {
  if (currentSubstep.value < substeps.length) {
    currentSubstep.value++
  }
  updateFormData()
}

// 保存老人信息并跳转
const saveElderAndNext = async () => {
  if (!isElderInfoValid.value) return
  
  elderLoading.value = true
  try {
    // 构造老人数据，手动添加 isDeleted: 1（未审核状态）
    const elderData = {
      ...localFormData.elder, // 原有老人信息（姓名、年龄等）
      // isDeleted: 1 // 前端强制添加：未审核时设为1
    };
    
    // 使用try-catch包装API调用，手动处理错误
    let response
    try {
      response = await addElderly(elderData)
    } catch (apiError) {
      // 检查是否是身份证重复错误
      const errorMsg = apiError.message || ''
      const responseMsg = apiError.response?.data?.msg || ''
      const fullErrorText = errorMsg + ' ' + responseMsg
      
      if (fullErrorText.includes('uk_id_card') || 
          fullErrorText.includes('Duplicate entry') || 
          fullErrorText.includes('身份证') ||
          fullErrorText.includes('SQLIntegrityConstraintViolationException')) {
        
        // 显示友好提示，不抛出错误
        ElMessage.warning('身份证有误，请重新输入')
        return
      } else {
        // 其他错误正常抛出
        throw apiError
      }
    }
    
    if (response.code === 200) {
      // 保存成功，获取老人ID
      const elderId = response.data
      
      // 🚀 修复：统一设置老人ID到两个位置
      localFormData.elderlyId = elderId
      localFormData.elder.id = elderId // 同时设置到elder对象中
      
      // 通知父组件老人信息已保存
      emit('elder-saved', elderId)
      
      // 更新表单数据
      updateFormData()
      
      // 跳转到下一步
      nextSubstep()
      
      // 显示成功提示
      ElMessage.success('老人信息添加成功！')
    } else {
      // 检查是否是身份证重复错误
      if (response.msg && (response.msg.includes('身份证') || response.msg.includes('uk_id_card') || response.msg.includes('Duplicate entry'))) {
        ElMessage.warning('身份证有误，请重新输入')
      } else {
        ElMessage.error('保存失败：' + response.msg)
      }
    }
  } catch (error) {
    console.error('保存老人信息失败:', error)
    
    // 检查错误信息中是否包含身份证重复的提示
    const errorMsg = error.message || ''
    const responseMsg = error.response?.data?.msg || ''
    const fullErrorText = errorMsg + ' ' + responseMsg
    
    // 如果是身份证重复错误，显示友好提示并阻止默认错误显示
    if (fullErrorText.includes('uk_id_card') || 
        fullErrorText.includes('Duplicate entry') || 
        fullErrorText.includes('身份证') ||
        fullErrorText.includes('SQLIntegrityConstraintViolationException')) {
      
      // 显示友好提示
      ElMessage.warning('身份证有误，请重新输入')
      
      return // 提前返回，避免执行后续的错误处理
    } else {
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    elderLoading.value = false
  }
}

// 保存家属信息并跳转
const saveFamilyAndNext = async () => {
  if (!isFamilyInfoValid.value) return;

  // 检查是否已保存老人信息（确保有elderlyId关联）
  if (!localFormData.elderlyId) {
    ElMessage.error('请先保存老人信息');
    return;
  }

  familyLoading.value = true;
  try {
    // 循环遍历家属列表，逐条保存
    for (const member of localFormData.familyMembers) {
      // 为每个家属添加老人ID（关联老人）
      const familyData = {
        ...member,
        elderlyId: localFormData.elderlyId
      };

      // 调用单条保存接口
      const response = await addMember(familyData);

      // 若单条保存失败，直接抛出错误（终止后续循环）
      if (response.code !== 200) {
        throw new Error(`保存家属【${member.name || '未知'}】失败：${response.msg}`);
      }
    }

    // 所有家属保存成功后，执行跳转
    nextSubstep();
    ElMessage.success('所有家属信息添加成功！');
  } catch (error) {
    console.error('保存家属信息失败:', error);
    ElMessage.error('保存失败：' + error.message);
  } finally {
    familyLoading.value = false;
  }
};

/**
 * 上传单个文件到若依接口，返回文件URL
 * @param {File} file - 待上传的文件对象
 * @param {string} fileType - 文件类型，用于生成唯一标识
 * @returns {string} 文件访问URL
 */
const uploadFile = async (file, fileType) => {
  if (!file) {
    throw new Error('文件对象为空，请重新选择文件');
  }
  
  if (!(file instanceof File)) {
    throw new Error('无效的文件类型，请选择正确的文件');
  }

  // 检查文件大小和类型
  const maxSize = 2 * 1024 * 1024; // 2MB
  if (file.size > maxSize) {
    throw new Error('文件大小不能超过2MB');
  }

  const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
  if (!validTypes.includes(file.type)) {
    throw new Error('只支持JPG、PNG格式的图片');
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const timestamp = Date.now();
    const response = await request({
      url: `/common/upload?t=${timestamp}&type=${fileType}`,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000 // 30秒超时
    });


    if (response && response.code === 200) {
      if (response.url) {
        return response.url;
      } else if (response.fileName) {
        return `/profile/upload/${response.fileName}`;
      } else if (response.data && response.data.url) {
        return response.data.url;
      } else if (response.data && response.data.fileName) {
        return `/profile/upload/${response.data.fileName}`;
      } else {
        throw new Error('接口返回格式异常，未找到文件URL');
      }
    } else {
      throw new Error(response?.msg || '上传失败，请重试');
    }

  } catch (error) {
    console.error(`${fileType} 文件上传详细错误:`, error);
    
    let errorMsg = '文件上传失败：';
    if (error.response && error.response.status) {
      const status = error.response.status;
      if (status === 413) {
        errorMsg += '文件太大，请压缩后上传';
      } else if (status === 415) {
        errorMsg += '不支持的文件类型';
      } else if (status >= 500) {
        errorMsg += '服务器内部错误，请稍后重试';
      } else {
        errorMsg += `服务器错误 (${status})`;
      }
    } else if (error.code === 'ECONNABORTED') {
      errorMsg += '上传超时，请检查网络连接';
    } else if (error.message && error.message.includes('Network Error')) {
      errorMsg += '网络错误，请检查网络连接';
    } else if (error.message && error.message.includes('重复提交')) {
      errorMsg += '检测到重复提交，请稍后重试或联系管理员';
    } else {
      errorMsg += error.message || '未知错误';
    }
    
    throw new Error(errorMsg);
  }
};

/**
 * 保存照片信息并进入下一步
 */
const savePhotosAndComplete = async () => {
  // 🚀 修复：明确使用 elderlyId 并添加调试信息
  const elderId = localFormData.elderlyId;

  if (!elderId) {
    ElMessage.error('请先保存老人基本信息，获取老人ID');
    return;
  }

  // 检查是否已上传所有必需文件
  const requiredFiles = ['photo', 'idCardFront', 'idCardBack'];
  const missingFiles = requiredFiles.filter(type => !localFormData.uploads[type]);
  
  if (missingFiles.length > 0) {
    const fileNames = missingFiles.map(type => {
      switch(type) {
        case 'photo': return '一寸照片';
        case 'idCardFront': return '身份证正面';
        case 'idCardBack': return '身份证反面';
        default: return type;
      }
    }).join('、');
    
    ElMessage.warning(`请先上传${fileNames}`);
    return;
  }

  // 检查是否上传了相同的文件
  const fileNames = Object.values(localFormData.uploads).map(file => file.name);
  const uniqueFileNames = [...new Set(fileNames)];
  if (uniqueFileNames.length < Object.keys(localFormData.uploads).length) {
    const confirm = await ElMessageBox.confirm(
      '检测到您上传了相同的文件，这可能导致上传失败。是否继续？',
      '提示',
      {
        confirmButtonText: '继续',
        cancelButtonText: '重新选择',
        type: 'warning'
      }
    ).catch(() => false);
    
    if (!confirm) {
      return;
    }
  }

  photoLoading.value = true;
  
  try {
    const uploadResults = [];
    const fileTypes = ['photo', 'idCardFront', 'idCardBack'];
    
    // 串行上传，避免同时上传多个文件
    for (const fileType of fileTypes) {
      const file = localFormData.uploads[fileType];
      if (file) {
        try {
          ElMessage.info(`正在上传${getFileTypeName(fileType)}...`);
          
          if (fileType !== 'photo') {
            await new Promise(resolve => setTimeout(resolve, 500));
          }
          
          const url = await uploadFile(file, fileType);
          uploadResults.push({ type: fileType, url });
        } catch (error) {
          throw new Error(`${getFileTypeName(fileType)}上传失败：${error.message}`);
        }
      }
    }

    // 🚀 修复：明确构建更新数据，避免使用展开运算符覆盖ID
    const updateData = {
      id: elderId, // 明确使用保存后获取的ID
      // 手动选择需要的老人字段，避免数据覆盖
      name: localFormData.elder.name,
      idCard: localFormData.elder.idCard,
      gender: localFormData.elder.gender,
      birthDate: localFormData.elder.birthDate,
      age: localFormData.elder.age,
      contact: localFormData.elder.contact,
      address: localFormData.elder.address,
      ethnicity: localFormData.elder.ethnicity,
      politicalStatus: localFormData.elder.politicalStatus,
      religiousBelief: localFormData.elder.religiousBelief,
      maritalStatus: localFormData.elder.maritalStatus,
      education: localFormData.elder.education,
      incomeSource: localFormData.elder.incomeSource,
      hobby: localFormData.elder.hobby,
      medicalInsurance: localFormData.elder.medicalInsurance,
      medicalCardNo: localFormData.elder.medicalCardNo,
      isDeleted: 1 // 保持审核状态
    };
    
    // 添加照片路径字段
    uploadResults.forEach(result => {
      if (result.type === 'photo') {
        updateData.photo = result.url;
      } else if (result.type === 'idCardFront') {
        updateData.idCardFront = result.url;
      } else if (result.type === 'idCardBack') {
        updateData.idCardBack = result.url;
      }
    });

    // 调用修改老人的接口
    const updateResponse = await updateElderly(updateData);
    
    if (updateResponse.code === 200) {
      ElMessage.success('照片信息上传并更新成功！');
      
      // ========== 新增：所有步骤完成后，添加数据到pending_tasks表 ==========
      await addToPendingTasks(elderId, localFormData.elder.name);
      
      setTimeout(() => {
        emit('next'); // 触发下一步
      }, 1000);
    } else {
      throw new Error(`更新老人信息失败：${updateResponse.msg || '未知错误'}`);
    }

  } catch (error) {
    console.error('保存照片信息完整错误:', error);
    ElMessage.error(error.message);
  } finally {
    photoLoading.value = false;
  }
};

// 文件类型名称映射
const getFileTypeName = (type) => {
  const typeMap = {
    photo: '一寸照片',
    idCardFront: '身份证正面',
    idCardBack: '身份证反面'
  };
  return typeMap[type] || type;
};


const prevSubstep = () => {
  if (currentSubstep.value > 1) {
    currentSubstep.value--
  }
  updateFormData()
}

// ========== 新增：生成8位code（前两位rz + 后六位随机数字） ==========
const generatePendingTaskCode = () => {
  const randomNum = Math.floor(100000 + Math.random() * 900000); // 生成6位随机数字
  return `rz${randomNum}`;
};

// ========== 新增：添加数据到pending_tasks表 ==========
const addToPendingTasks = async (elderId, elderName) => {
  try {
    // 检查是否有当前用户信息
    if (!props.currentUser || !props.currentUser.id) {
      return;
    }

    const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    
    const pendingTaskData = {
      code: generatePendingTaskCode(),
      title: `${elderName}入住申请`,
      type: 3,
      assignee: props.currentUser.nickName || props.currentUser.name || '',
      assigneeId: props.currentUser.id,
      status: 1,
      applicationTime: currentTime,
      applicat: props.currentUser.nickName || props.currentUser.name || '',
      applicatId: props.currentUser.id,
      extraField2: elderId, // 老人ID
      createBy: props.currentUser.id,
      updateBy: props.currentUser.id,
      isHandle: 0,
      createTime: currentTime
    };

    const response = await addPendingTasks(pendingTaskData);
    
    if (response.code === 200) {
      // 成功添加
    } else {
      console.error('pending_tasks数据添加失败:', response.msg);
    }
  } catch (error) {
    console.error('添加pending_tasks数据时发生错误:', error);
  }
};

const completeStep = () => {
  updateFormData()
  emit('next')
}

// 更新表单数据
const updateFormData = () => {
  emit('update:form-data', localFormData)
}

// 家属信息操作方法
const addFamilyMember = () => {
  localFormData.familyMembers.push({
    name: "",
    contact: "",
    relationship: "",
    isEmergency: "否",
  })
  updateFormData()
}

const removeFamilyMember = (index) => {
  if (localFormData.familyMembers.length > 1) {
    localFormData.familyMembers.splice(index, 1)
    updateFormData()
  }
}

// 文件上传方法
const triggerFileInput = (type) => {
  switch (type) {
    case "photo":
      photoInput.value?.click()
      break
    case "idCardFront":
      idCardFrontInput.value?.click()
      break
    case "idCardBack":
      idCardBackInput.value?.click()
      break
  }
}

const handleUpload = async (type, e) => {
  const file = e.target.files[0]
  if (!file) return

  const validTypes = ['image/jpeg', 'image/png', 'image/jpg']
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请上传JPG或PNG格式的图片')
    resetFileInput(type)
    return
  }

  const maxSize = 2 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过2MB')
    resetFileInput(type)
    return
  }

  localFormData.uploads[type] = file

  try {
    const originalPreviewUrl = URL.createObjectURL(file)
    previewUrls.value[type] = originalPreviewUrl

    setTimeout(async () => {
      try {
        const compressedDataUrl = await compressImage(file)
        previewUrls.value[type] = compressedDataUrl
        URL.revokeObjectURL(originalPreviewUrl)
      } catch (compressError) {
        console.error('图片压缩失败，使用原始图片:', compressError)
      }
    }, 100)
    
  } catch (error) {
    console.error('图片处理失败:', error)
    ElMessage.error('图片处理失败，请重试')
    clearUpload(type)
  }
  
  updateFormData()
}

const compressImage = (file) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    img.onload = () => {
      let width = img.width
      let height = img.height
      
      const maxDimension = 600
      if (width > maxDimension || height > maxDimension) {
        if (width > height) {
          height = (height * maxDimension) / width
          width = maxDimension
        } else {
          width = (width * maxDimension) / height
          height = maxDimension
        }
      }
      
      canvas.width = width
      canvas.height = height
      
      ctx.drawImage(img, 0, 0, width, height)
      const compressedDataUrl = canvas.toDataURL(file.type, 0.7)
      resolve(compressedDataUrl)
    }
    
    img.onerror = reject
    img.src = URL.createObjectURL(file)
  })
}

const resetFileInput = (type) => {
  switch (type) {
    case "photo":
      if (photoInput.value) photoInput.value.value = ""
      break
    case "idCardFront":
      if (idCardFrontInput.value) idCardFrontInput.value.value = ""
      break
    case "idCardBack":
      if (idCardBackInput.value) idCardBackInput.value.value = ""
      break
  }
}

const clearUpload = (type) => {
  localFormData.uploads[type] = null
  previewUrls.value[type] = ""
  resetFileInput(type)
  updateFormData()
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 Bytes"
  const k = 1024
  const sizes = ["Bytes", "KB", "MB"]
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
}
</script>

<style scoped>
.step-panel h2 {
  color: #1f2937;
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

/* 子步骤样式 */
.substeps-nav {
  display: flex;
  margin: 20px 0 30px;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 10px;
}

.substep-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 30px;
  color: #6b7280;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.substep-item:hover:not(.substep-disabled) {
  color: #3b82f6;
}

.substep-item span:first-child {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #e5e7eb;
  color: #6b7280;
  text-align: center;
  line-height: 24px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.substep-active {
  color: #3b82f6;
}

.substep-active span:first-child {
  background-color: #3b82f6;
  color: white;
}

.substep-completed {
  color: #10b981;
}

.substep-completed span:first-child {
  background-color: #10b981;
  color: white;
}

.substep-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

/* 表单样式 */
.substep-content {
  margin: 20px 0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #4b5563;
  font-weight: 500;
}

.required {
  color: #ef4444;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.radio-group {
  display: flex;
  gap: 20px;
  margin-top: 8px;
  flex-wrap: wrap;
}

.radio-group label {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 0;
}

/* 家属信息样式 */
.family-members {
  margin-bottom: 20px;
}

.family-member-card {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  position: relative;
}

.remove-btn {
  background-color: #fef2f2;
  color: #dc2626;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
}

.add-btn {
  background-color: #eff6ff;
  color: #2563eb;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 30px;
}

/* 上传区域样式 */
.upload-group {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.upload-item {
  margin-bottom: 10px;
}

.upload-item label {
  display: block;
  margin-bottom: 12px;
  color: #4b5563;
  font-weight: 500;
}

.upload-wrapper {
  width: 280px;
}

.upload-area {
  width: 100%;
  height: 200px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #f9fafb;
}

.upload-input {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
  z-index: 10;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  text-align: center;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.preview-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 6px;
}

.file-info {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #9ca3af;
}

/* 按钮区域样式 */
.substep-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 40px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

button:nth-of-type(1) {
  background-color: #f3f4f6;
  color: #1f2937;
}

button:nth-of-type(2),
button:last-child {
  background-color: #3b82f6;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .upload-wrapper {
    width: 100%;
  }
  
  .substeps-nav {
    flex-direction: column;
    gap: 10px;
  }
  
  .substep-item {
    margin-right: 0;
  }
}
</style>
